﻿using System;
using System.CodeDom.Compiler;
using System.Globalization;
using Microsoft.CSharp;
using DslModeling=global::Microsoft.VisualStudio.Modeling;
using DslDiagrams=global::Microsoft.VisualStudio.Modeling.Diagrams;
using DslValidation=global::Microsoft.VisualStudio.Modeling.Validation;

namespace Salamanca.Sdml
{

    partial class NamedElement
    {
        partial class NamePropertyHandler
        {
            protected override void OnValueChanging(NamedElement element, string oldValue, string newValue)
            {
                if (!element.Store.InUndoRedoOrRollback)
                    if (string.IsNullOrEmpty(newValue))
                        throw new ArgumentOutOfRangeException("Name", Resources.SR.NameCannotBeNull);

                base.OnValueChanging(element, oldValue, newValue);
            }
        }

        /// <summary>Ensures that names will be valid C# identifiers.</summary>
        [DslValidation.ValidationMethod(DslValidation.ValidationCategories.Menu | DslValidation.ValidationCategories.Open | DslValidation.ValidationCategories.Save)]
        private void ValidateName(DslValidation.ValidationContext context)
        {
            if (!(new CSharpCodeProvider().IsValidIdentifier(Name)))
                context.LogError(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.SR.InvalidName,
                        Name
                    ),
                    "SDML08",
                    this
                );
        }
    }
}
